package com.cloud.configure;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置类
 *
 * @author yzj
 */
@Configuration
public class RedisConfiguration extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.activateDefaultTyping(new LaissezFaireSubTypeValidator(), ObjectMapper.DefaultTyping.EVERYTHING);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // Json 序列化配置
        GenericJackson2JsonRedisSerializer JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(mapper);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // Key 采用String 的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // Hash 的key 也采用String 的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // Value 序列化方式采用jackson
        template.setValueSerializer(JsonRedisSerializer);
        // Hash 的Value 序列化方式采用jackson
        template.setHashValueSerializer(JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

}